package cn.cachalot.oj.util;

import cn.cachalot.oj.entity.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class TokenUtil {
    private static final String SECRET = "Ld9}4gvb!6";
    //过期时间30分钟
    private static final long EXPIRE_TIME = 2 * 60 * 60 * 1000L;

    public static String creatToken(User user) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
//            return JWT.create()
//                    //将userId保存到token里面
//                    .withAudience(user.getId().toString(), user.getLevel().toString())
//                    .withExpiresAt(date)
//                    //token的密钥
//                    .sign(algorithm);
            return JWT.create().withClaim("userId", user.getId().toString())
                    .withClaim("userLevel", user.getLevel().toString()).withExpiresAt(date).sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String getUserIdFromToken(String token) {
        try {
//            return JWT.decode(token).getAudience().get(0);
            return JWT.decode(token).getClaim("userId").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static Integer getUserLevelFromToken(String token) {
        try {
//            return Integer.parseInt(JWT.decode(token).getAudience().get(1));
            return Integer.parseInt(JWT.decode(token).getClaim("userLevel").asString());
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static boolean checkToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            //            throw new RuntimeException("token无效");
            log.info("token无效");
            return false;
        }
    }

}